/**
 * PerformanceOptimizationDemo - 性能优化系统演示
 * 展示如何使用对象池、渲染优化和性能监控系统
 * @class
 */

import { GameEngine } from './GameEngine'
import { gameObjectPools, PoolableParticle } from './GameObjectPools'
import { Entity, EntityType } from './Entity'

/**
 * 性能优化演示类
 * 展示各种性能优化技术的使用方法
 */
export class PerformanceOptimizationDemo {
  private gameEngine: GameEngine
  private particles: PoolableParticle[] = []
  private demoRunning: boolean = false

  /**
   * 创建性能优化演示
   * @param canvasId - Canvas元素ID
   */
  constructor(canvasId: string) {
    // 创建游戏引擎，启用所有性能优化功能
    this.gameEngine = new GameEngine({
      canvasId,
      width: 800,
      height: 600,
      targetFPS: 60,
      enablePerformanceMonitoring: true,
      renderOptimizerOptions: {
        enableFrustumCulling: true,
        enableBatching: true,
        frustumMargin: 50,
        maxBatchSize: 50
      },
      performanceThresholds: {
        minFPS: 45,
        maxFrameTime: 22, // ~45 FPS
        maxMemoryUsage: 150, // 150MB
        maxRenderTime: 12 // ~83 FPS
      }
    })

    // 预热对象池
    this.warmUpObjectPools()
  }

  /**
   * 预热对象池，提前创建常用对象
   */
  private warmUpObjectPools(): void {
    console.log('🔥 预热对象池...')
    
    // 预热各种对象池
    gameObjectPools.warmUpPools(100, 50, 30)
    
    const stats = gameObjectPools.getPoolStats()
    console.log('📊 对象池统计:', stats)
  }

  /**
   * 开始性能优化演示
   */
  startDemo(): void {
    console.log('🚀 开始性能优化演示')
    
    this.demoRunning = true
    this.gameEngine.start()
    
    // 开始性能基准测试
    this.startPerformanceBenchmarks()
    
    // 创建大量粒子效果来测试对象池
    this.createParticleEffects()
    
    // 定期输出性能报告
    this.startPerformanceReporting()
  }

  /**
   * 停止演示
   */
  stopDemo(): void {
    console.log('⏹️ 停止性能优化演示')
    
    this.demoRunning = false
    this.gameEngine.stop()
    
    // 清理所有粒子
    this.cleanupParticles()
    
    // 输出最终性能报告
    this.generateFinalReport()
  }

  /**
   * 开始性能基准测试
   */
  private startPerformanceBenchmarks(): void {
    const monitor = this.gameEngine.getPerformanceMonitor()
    
    // 测试对象池性能
    monitor.startBenchmark('object-pool-performance')
    
    const startTime = performance.now()
    
    // 大量创建和销毁对象
    for (let i = 0; i < 1000; i++) {
      const particle = gameObjectPools.getParticle()
      if (particle) {
        particle.initialize(
          Math.random() * 800,
          Math.random() * 600,
          (Math.random() - 0.5) * 200,
          (Math.random() - 0.5) * 200,
          Math.random() * 2 + 0.5,
          `hsl(${Math.random() * 360}, 70%, 50%)`
        )
        
        // 立即归还到池中
        particle.active = false
        particle.visible = false
        gameObjectPools.returnParticle(particle)
      }
    }
    
    const duration = monitor.endBenchmark()
    console.log(`⚡ 对象池性能测试: ${duration.toFixed(2)}ms (1000次创建/销毁)`)
  }

  /**
   * 创建粒子效果来测试性能优化
   */
  private createParticleEffects(): void {
    const entityManager = this.gameEngine.getEntityManager()
    
    // 创建大量粒子
    for (let i = 0; i < 200; i++) {
      const particle = gameObjectPools.createParticle(
        Math.random() * 800,
        Math.random() * 600,
        (Math.random() - 0.5) * 100,
        (Math.random() - 0.5) * 100,
        Math.random() * 3 + 1,
        `hsl(${Math.random() * 360}, 70%, 60%)`
      )
      
      if (particle) {
        this.particles.push(particle)
        entityManager.addEntity(particle)
      }
    }
    
    console.log(`✨ 创建了 ${this.particles.length} 个粒子`)
  }

  /**
   * 清理粒子
   */
  private cleanupParticles(): void {
    const entityManager = this.gameEngine.getEntityManager()
    
    // 移除所有粒子并归还到对象池
    this.particles.forEach(particle => {
      entityManager.removeEntity(particle.id)
      particle.active = false
      particle.visible = false
      gameObjectPools.returnParticle(particle)
    })
    
    this.particles.length = 0
    console.log('🧹 清理了所有粒子')
  }

  /**
   * 开始定期性能报告
   */
  private startPerformanceReporting(): void {
    const reportInterval = setInterval(() => {
      if (!this.demoRunning) {
        clearInterval(reportInterval)
        return
      }
      
      this.generatePerformanceReport()
    }, 5000) // 每5秒输出一次报告
  }

  /**
   * 生成性能报告
   */
  private generatePerformanceReport(): void {
    const monitor = this.gameEngine.getPerformanceMonitor()
    const renderOptimizer = this.gameEngine.getRenderOptimizer()
    const entityManager = this.gameEngine.getEntityManager()
    
    console.group('📈 性能报告')
    
    // 基本性能指标
    const metrics = monitor.getMetrics()
    console.log(`FPS: ${metrics.fps.toFixed(1)}`)
    console.log(`平均帧时间: ${metrics.averageFrameTime.toFixed(2)}ms`)
    console.log(`渲染时间: ${metrics.renderTime.toFixed(2)}ms`)
    console.log(`更新时间: ${metrics.updateTime.toFixed(2)}ms`)
    console.log(`内存使用: ${metrics.memoryUsage.usedJSHeapSize.toFixed(1)}MB`)
    
    // 渲染优化统计
    const renderStats = renderOptimizer.getStats()
    console.log(`实体总数: ${renderStats.totalEntities}`)
    console.log(`渲染实体: ${renderStats.renderedEntities}`)
    console.log(`剔除率: ${renderStats.cullRate.toFixed(1)}%`)
    console.log(`批次数量: ${renderStats.batchCount}`)
    
    // 实体管理统计
    const entityStats = entityManager.getStats()
    console.log(`实体管理器统计:`, entityStats)
    
    // 对象池统计
    const poolStats = gameObjectPools.getPoolStats()
    console.log(`对象池统计:`, poolStats)
    
    // 性能健康检查
    const health = monitor.isPerformanceHealthy()
    if (!health.healthy) {
      console.warn('⚠️ 性能问题:', health.issues)
    }
    
    // 最近的警告
    const recentAlerts = monitor.getRecentAlerts(3)
    if (recentAlerts.length > 0) {
      console.warn('🚨 最近警告:', recentAlerts)
    }
    
    console.groupEnd()
  }

  /**
   * 生成最终性能报告
   */
  private generateFinalReport(): void {
    const monitor = this.gameEngine.getPerformanceMonitor()
    
    console.group('📋 最终性能报告')
    
    // 完整的性能报告
    const fullReport = monitor.generateReport()
    console.log(fullReport)
    
    // 基准测试结果
    const benchmarkResults = monitor.getAllBenchmarkResults()
    console.log('🏁 基准测试结果:', benchmarkResults)
    
    // 对象池最终统计
    const finalPoolStats = gameObjectPools.getPoolStats()
    console.log('🎯 对象池最终统计:', finalPoolStats)
    
    console.groupEnd()
  }

  /**
   * 动态调整性能设置
   * @param settings - 性能设置
   */
  adjustPerformanceSettings(settings: {
    targetFPS?: number
    enableFrustumCulling?: boolean
    enableBatching?: boolean
    maxBatchSize?: number
  }): void {
    console.log('⚙️ 调整性能设置:', settings)
    
    const renderOptimizer = this.gameEngine.getRenderOptimizer()
    
    if (settings.targetFPS !== undefined) {
      this.gameEngine.setTargetFPS(settings.targetFPS)
    }
    
    if (settings.enableFrustumCulling !== undefined) {
      renderOptimizer.setFrustumCullingEnabled(settings.enableFrustumCulling)
    }
    
    if (settings.enableBatching !== undefined) {
      renderOptimizer.setBatchingEnabled(settings.enableBatching)
    }
    
    if (settings.maxBatchSize !== undefined) {
      renderOptimizer.setMaxBatchSize(settings.maxBatchSize)
    }
  }

  /**
   * 压力测试 - 创建大量实体来测试性能
   * @param entityCount - 要创建的实体数量
   */
  stressTest(entityCount: number = 500): void {
    console.log(`🔥 开始压力测试 - 创建 ${entityCount} 个实体`)
    
    const monitor = this.gameEngine.getPerformanceMonitor()
    const entityManager = this.gameEngine.getEntityManager()
    
    monitor.startBenchmark('stress-test')
    
    const stressEntities: PoolableParticle[] = []
    
    // 创建大量实体
    for (let i = 0; i < entityCount; i++) {
      const particle = gameObjectPools.createParticle(
        Math.random() * 1600 - 400, // 扩大范围，测试视锥剔除
        Math.random() * 1200 - 300,
        (Math.random() - 0.5) * 300,
        (Math.random() - 0.5) * 300,
        Math.random() * 5 + 1,
        `hsl(${Math.random() * 360}, 80%, 50%)`
      )
      
      if (particle) {
        stressEntities.push(particle)
        entityManager.addEntity(particle)
      }
    }
    
    const creationTime = monitor.endBenchmark()
    console.log(`⚡ 实体创建耗时: ${creationTime.toFixed(2)}ms`)
    
    // 运行一段时间后清理
    setTimeout(() => {
      monitor.startBenchmark('stress-cleanup')
      
      stressEntities.forEach(particle => {
        entityManager.removeEntity(particle.id)
        particle.active = false
        particle.visible = false
        gameObjectPools.returnParticle(particle)
      })
      
      const cleanupTime = monitor.endBenchmark()
      console.log(`🧹 实体清理耗时: ${cleanupTime.toFixed(2)}ms`)
      console.log('✅ 压力测试完成')
    }, 10000) // 10秒后清理
  }

  /**
   * 获取当前性能指标
   * @returns 性能指标对象
   */
  getCurrentMetrics(): {
    fps: number
    frameTime: number
    renderTime: number
    memoryUsage: number
    entityCount: number
    cullRate: number
  } {
    const monitor = this.gameEngine.getPerformanceMonitor()
    const renderOptimizer = this.gameEngine.getRenderOptimizer()
    const entityManager = this.gameEngine.getEntityManager()
    
    const metrics = monitor.getMetrics()
    const renderStats = renderOptimizer.getStats()
    
    return {
      fps: metrics.fps,
      frameTime: metrics.averageFrameTime,
      renderTime: metrics.renderTime,
      memoryUsage: metrics.memoryUsage.usedJSHeapSize,
      entityCount: entityManager.getEntityCount(),
      cullRate: renderStats.cullRate
    }
  }
}

/**
 * 创建性能优化演示实例的工厂函数
 * @param canvasId - Canvas元素ID
 * @returns 演示实例
 */
export function createPerformanceDemo(canvasId: string): PerformanceOptimizationDemo {
  return new PerformanceOptimizationDemo(canvasId)
}

/**
 * 性能优化最佳实践指南
 */
export const PerformanceOptimizationGuide = {
  /**
   * 对象池使用建议
   */
  objectPoolBestPractices: [
    '为频繁创建/销毁的对象使用对象池',
    '预热对象池以避免运行时分配',
    '设置合理的池大小限制',
    '及时归还不再使用的对象',
    '监控池的命中率和使用情况'
  ],

  /**
   * 渲染优化建议
   */
  renderOptimizationTips: [
    '启用视锥剔除减少不必要的渲染',
    '使用批量渲染减少绘制调用',
    '按渲染类型和纹理分组实体',
    '合理设置批次大小',
    '监控剔除率和批次数量'
  ],

  /**
   * 性能监控建议
   */
  performanceMonitoringTips: [
    '设置合理的性能阈值',
    '定期检查性能健康状态',
    '使用基准测试比较优化效果',
    '监控内存使用避免泄漏',
    '关注性能警告并及时优化'
  ],

  /**
   * 通用性能优化建议
   */
  generalOptimizationTips: [
    '避免在游戏循环中创建临时对象',
    '使用高效的数据结构和算法',
    '合理控制游戏实体数量',
    '优化碰撞检测和物理计算',
    '定期进行性能分析和优化'
  ]
}